package com.thread.thread.Condition之生产者与消费者;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionTest {
	ReentrantLock reentrantLock=new ReentrantLock();

	Condition producer = reentrantLock.newCondition();
	Condition consumer = reentrantLock.newCondition();
	int MAX=10;
	int count=0;
	public void put(){
		try {
			reentrantLock.lock();
			while(count==MAX){
				try {
					producer.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println("开始生产");
			count++;
			consumer.signalAll();
		} finally {
			reentrantLock.unlock();
		}

	}




	public  void   get(){
		try {
			reentrantLock.lock();
			while (count==0){
				try {
					consumer.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
			System.out.println("开始消费");
			count--;
			producer.signalAll();
		} finally {
			reentrantLock.unlock();
		}

	}


	public static void main(String[] args) {


		ConditionTest conditionTest=new ConditionTest();

		new  Thread(()->{
			while (true){
				conditionTest.put();
			}


		}).start();
		new  Thread(()->{
			while (true){
				conditionTest.get();
			}


		}).start();

	}


}
